#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <unistd.h>
#include <sys/times.h>
#include <sys/time.h>
#include <time.h>

void do_sum(int count)
{
    int sum = 0;
    for (int i = 0; i < count; i++) {
        sum += i;
    }
    FILE *fp = fopen("/dev/null", "w");
    fprintf(fp, "%d\n", sum);
    fclose(fp);
}

decltype(clock()) last_clock = 0;
uint64_t last_time = 0;

void init_cpu_load()
{
    last_clock = clock();
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    last_time = (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}

void print_cpu_load(const char *str)
{
    decltype(clock()) current_clock = clock();
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    uint64_t current_time = (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
    printf("%s: clock=%" PRIu64 "\ttime=%" PRIu64 "\tcpu_load: %lf%%\n", str,
            current_clock - last_clock,
            current_time - last_time,
            (current_clock - last_clock) * 1000.0 * 100 / (current_time - last_time));
    last_clock = current_clock;
    last_time = current_time;
}

int main()
{
    while (true) {
        init_cpu_load();
        usleep(10 * 1000);
        print_cpu_load("  0");

        do_sum(2e3);
        usleep(1 * 1000);
        print_cpu_load("2e3");

        do_sum(2e5);
        usleep(1 * 1000);
        print_cpu_load("2e5");

        do_sum(2e6);
        usleep(1 * 1000);
        print_cpu_load("2e6");

        do_sum(2e4);
        usleep(1 * 1000);
        print_cpu_load("2e4");
        printf("\n");
    }
    return 0;
}
